package com.prothink.threadproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.prothink.threadproject.entity.FormLogin;
import com.prothink.threadproject.entity.User;
import com.prothink.threadproject.exception.BisnessException;
import com.prothink.threadproject.mapper.LoginMapper;
import com.prothink.threadproject.mapper.UserMapper;
import com.prothink.threadproject.service.UserService;
import com.prothink.threadproject.util.JWTToken;
import com.prothink.threadproject.util.Md5Util;
import com.prothink.threadproject.util.PwdUtil;
import com.prothink.threadproject.vo.AccountForm;
import com.prothink.threadproject.vo.ForgetPwdVo;
import com.prothink.threadproject.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private ApplicationContext applicationContext;
    // ServiceImpl 已经实现了常用的 CRUD 方法

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Override
    public int updateUserPassword(Long id, String newPassword) {
        // 根据用户ID查询用户信息并更新密码
        FormLogin formLogin = getFormById(id);
        if (formLogin != null) {

            // 调用更新方法，将加密后的密码保存到数据库
            return updateForm(formLogin);
        }
        return 0; // 更新失败，返回0
    }

    public FormLogin getFormById(Long id){
        return loginMapper.selectById(id);
    }


    // 模糊查询用户
    @Override
    public List<User> searchUsers(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name); // 使用 `like` 方法进行模糊查询
        return userMapper.selectList(queryWrapper);
    }
    // 新建用户
    public int createUser(User user) {
        // 设置创建用户的操作人
        if (user.getCUser() == null || user.getCUser().isEmpty()) {
            user.setCUser("default_user");  // 可改为动态获取当前登录用户
        }
        return userMapper.insert(user);
    }
    // 根据 ID 删除用户
    public int deleteUserById(Long id) {
        return userMapper.deleteById(id);  // MyBatis Plus deleteById 方法返回影响的行数
    }
    // 更新用户信息
    // 更新用户信息
    @Override
    public int updateUser(User user) {
        // 设置更新用户的操作人
        if (user.getUUser() == null || user.getUUser().isEmpty()) {
            user.setUUser("默认用户");  // 可改为动态获取当前登录用户
        }
        return userMapper.updateById(user);
    }
    public User getUserById(Long id) {
        return userMapper.selectById(id);  // MyBatis Plus selectById 方法
    }

    // 查询所有用户
    public List<User> getAllUsers() {
        return userMapper.selectList(null);  // MyBatis Plus selectList 查询所有数据
    }



    @Override
    public void registUser(AccountForm accountForm){
        FormLogin userEntity = getUserByName(accountForm.getAccount());
        if (userEntity !=null){
            throw new BisnessException("该用户已注册:" + accountForm.getAccount());
        }
        FormLogin user = new FormLogin();
        user.setAccount(accountForm.getAccount());
        user.setPwd(Md5Util.md5Encript(accountForm.getPwd()));
        user.setEmail(accountForm.getEmail());
        loginMapper.insertUser(user);
    }
    @Override
    // 登录方法接收 AccountForm 对象
    public UserInfoVo login(AccountForm accountForm) {
        FormLogin userByName = getUserByName(accountForm.getAccount());
        if (userByName == null){
            throw new BisnessException("该用户不存在" + userByName.getAccount());
        }
        if (!userByName.getPwd().equals(Md5Util.md5Encript(accountForm.getPwd()))){
            throw new BisnessException("密码错误:" + userByName.getAccount());
        }
        String token = JWTToken.getToken(accountForm.getAccount());

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userByName,userInfoVo);
        userInfoVo.setToken(token);
        return userInfoVo;
    }
    @Override
    public FormLogin getUserByName(String account){
        QueryWrapper<FormLogin> wrapper = new QueryWrapper();
        wrapper.eq("account",account);
        return loginMapper.selectOne(wrapper);
    }

    @Override
    public void resetPwd(ForgetPwdVo forgetPwdVo) {
        /**
         * 查询用户的邮箱
         * 问题:
         * Spring事务失效场景:
         * 1. 方法的内部调用
         */
        UserService userService = applicationContext.getBean(UserService.class);
        FormLogin user = this.getUserByName(forgetPwdVo.getAccount());

        //2 生成随机密码
        String password = PwdUtil.generatorPassword();

        //邮件发送
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //邮件主题
        simpleMailMessage.setSubject("重置密码");
        //邮件正文
        simpleMailMessage.setText("您的新密码是: " + password);
        simpleMailMessage.setTo(user.getEmail());
        simpleMailMessage.setFrom("19322078098.163com");

        mailSender.send(simpleMailMessage);

        //更新密码到数据库
        //update user set password = ${pwd}
        FormLogin formLogin = new FormLogin();
        formLogin.setPwd(password);
        formLogin.setId(formLogin.getId());
        this.updateForm(formLogin);

        //创建复杂邮件的对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();
    }

    @Override
    public int updateForm(FormLogin formLogin) {
        // 调用 MyBatis 的 updateById 方法，并返回受影响的行数
        return loginMapper.updateById(formLogin);
    }

    @Async("myThreadPool")
    public void sendMail(FormLogin user, String password) {
        try {
            //创建复杂邮件的对象
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //设置标题
            mimeMessageHelper.setSubject("重置密码");
            String htmlText = "<table><tr><th>账号：</th><th>密码：</th></tr><tr><td>%s</td><td>%s</td></tr></table>";
            htmlText = String.format(htmlText, user.getAccount(), password);
            mimeMessageHelper.setText(htmlText, true);

            //设置邮件附件 文件名称有中文可能会乱码
            File file = new File("D:/files/13大数据2309-C第十三单元日测.docx");
            mimeMessageHelper.addAttachment("13大数据2309-C第十三单元日测", file);

            // 使用 encodeText、encodeWord 必须加上不截取配置
            System.getProperties().setProperty("mail.mime.splitlongparameters", "false");

            mimeMessageHelper.addAttachment(MimeUtility.encodeWord("13大数据2309-C第十三单元日测", "UTF-8", "B"), file);
            mimeMessageHelper.setTo(user.getEmail());
            mimeMessageHelper.setFrom("19322078098@163.com");

            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
